package com.efounder.agency.activity;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.activity.AbActivity;
import com.efounder.agency.utils.TableGenerator;
import com.efounder.agency.utils.TaskDataParser;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.eai.data.JResponseObject;
import com.efounder.forwechat.BaseApp;
import com.efounder.http.utils.GetContractData;
import com.efounder.ospmobilelib.R;
import com.efounder.util.AndroidEnvironmentVariable;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.view.titlebar.AbTitleBar;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

/*
 * @author yqs
 * 任务中心详情二级界面
 */
public class TaskDetaiSecondActivity extends AbActivity implements OnClickListener {

	private static final String TAG = "TaskDetailsecondActivity";

	AbTitleBar mTitleBar;
	
	LinearLayout scrollLinearLayout;
	
//	GridGenerator gridGenerator;
	
	EFRowSet flowRowSet = null;
	String type;
	String value;
	String itemId;// 请求的详情页数据的id
	String usereId;// 用户id
	String userName;// 用户名
	String password;// 用户密码
	
	private TableGenerator tableGenerator;
	private TaskDataParser taskDataParser;
	private EFDataSet tableDataSet;
	private ScrollView scrollView;
	
	AsyncTask<Void, Void, JResponseObject> asyncTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		BaseApp.actManager.putActivity(TAG, this);
		setAbContentView(R.layout.task_detail_dynamic_activity);
		initView();
		initData();
		
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (asyncTask != null) {
			asyncTask.cancel(true);
		}
	}
	@Override
	protected void onDestroy() {
		Log.i("", "------===========生命周期测试：onDestroy");
		super.onDestroy();
		if (asyncTask != null) {
			asyncTask=null;
		}
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			BaseApp.actManager.removeActivity(TAG);
			return false;
		}else {
			return super.onKeyDown(keyCode, event);
		}

	}
	/**
	 * 初始化view
	 */
	private void initView() {

		mTitleBar = this.getTitleBar();
		mTitleBar.setTitleText("单据信息");
//		mTitleBar.setLogo(R.drawable.button_selector_back);
		mTitleBar.setLogo(R.drawable.ef_title_view_back);
		mTitleBar.clearRightView();
		mTitleBar.setTitleBarGravity(Gravity.CENTER, Gravity.CENTER);
		mTitleBar.setLogoOnClickListener(this);
		// 得到bundle传递的数据
		Bundle bundle = getIntent().getBundleExtra("dataSource");
		if (bundle != null) {
			flowRowSet = (EFRowSet) bundle.getSerializable("data");
			type = (String) bundle.getSerializable("type");
			value = (String) bundle.getSerializable("value");
		}

		scrollLinearLayout = (LinearLayout) findViewById(R.id.scrollLinearLayout);
		scrollView = (ScrollView) findViewById(R.id.scrollview);
		
		// 初始化tableGenerator
		tableGenerator = new TableGenerator(this,"");
		taskDataParser = new TaskDataParser(this);
		LinearLayout linearLayout =(LinearLayout) findViewById(R.id.agency_bottom_container);
		linearLayout.setVisibility(View.GONE);
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		usereId = AndroidEnvironmentVariable.getUserID();// 用户id
		userName = AndroidEnvironmentVariable.getUserName();// 用户名
		password = AndroidEnvironmentVariable.getPassword();// 用户密码
		// 根据itemid请求数据
		if (value != null) {

	
			Log.i(TAG, "value:" + value);

			loadDataByNet();
		} else {
			Toast.makeText(this, "获取数据失败！", Toast.LENGTH_SHORT).show();
		}

	}

	@Override
	public void onClick(View v) {

		int id = v.getId();
		if (id == R.id.button_back) {
			// this.finish();
			BaseApp.actManager.removeActivity(TAG);
		} else if (v == mTitleBar.getLogoView()) {
			BaseApp.actManager.removeActivity(TAG);
		}
	}

	/**
	 * 显示或者隐藏gridlayout
	 * 
	 * @param layout
	 */
	private void showOrHideGridLay(LinearLayout layout, ImageView imageView,
			TextView textView) {
		if (layout.getChildCount() == 0) {
			//TODO　点击 生成子节点
			TextView testTextView = new TextView(TaskDetaiSecondActivity.this);
			testTextView.setText("test");
			layout.addView(testTextView);
		}
		if (layout.getVisibility() == View.VISIBLE) {
			layout.setVisibility(View.GONE);
			textView.setTextColor(this.getResources().getColor(R.color.shenhui));
			imageView.setImageDrawable(this.getResources().getDrawable(
					R.drawable.bills_dowm));
		} else if (layout.getVisibility() == View.GONE) {
			layout.setVisibility(View.VISIBLE);
			textView.setTextColor(this.getResources().getColor(
					R.color.billdetail_title));
			imageView.setImageDrawable(this.getResources().getDrawable(
					R.drawable.bills_top));
		}

	}

	/**
	 * 通过网络 加载数据
	 */
	private void loadDataByNet() {
		asyncTask = new AsyncTask<Void, Void, JResponseObject>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// 加载dialog显示
				LoadingDataUtilBlack.show(TaskDetaiSecondActivity.this);
			}

			@Override
			protected JResponseObject doInBackground(Void... params) {

				JResponseObject RO = null;
				// 判断是OA的还是合同的详情信息，以此来向服务器请求数据
				if (type.equals("form")) {
					RO = GetContractData.getSecondDate(value);
				} else if (type.equals("html")) {
					RO = GetContractData.gethtmlDate(value);
				}
				return RO;
			}

			@Override
			protected void onPostExecute(JResponseObject result) {

				super.onPostExecute(result);
			
				if (result != null) {
					@SuppressWarnings("unused")
					List<List<EFRowSet>> lists = new ArrayList<List<EFRowSet>>();
					@SuppressWarnings("unchecked")
					Map<String, Map<String, EFDataSet>> map = result.getResponseMap();
					// 1 DataSet
					EFDataSet dataSet = (EFDataSet) map.get("CONTRACT");
					if (type.equals("html")) {
						EFRowSet htmlEfRowSet = (EFRowSet) dataSet.getRowSetList().get(0);
						@SuppressWarnings("unused")
						String html = (String)htmlEfRowSet.getString("Html", "");
						System.out.println("html:"+ html);
						//生成webview
						WebView webView = new WebView(TaskDetaiSecondActivity.this);
						LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
						webView.setLayoutParams(params);
						webView.setOnTouchListener(new OnTouchListener() {
						
								      @Override
								      public boolean onTouch(View v, MotionEvent event) {
								        // TODO Auto-generated method stub
								        if (event.getAction() == MotionEvent.ACTION_UP) 
								          scrollView.requestDisallowInterceptTouchEvent(false); 
								              else  
								              scrollView.requestDisallowInterceptTouchEvent(true);
						
								              return false; 
								      }
						
						
								      });
						
						// 设置是否可缩放
						webView.getSettings().setSupportZoom(true);
						//出现缩放工具
						webView.getSettings().setBuiltInZoomControls(true);
						webView.getSettings().setJavaScriptEnabled(true);
								webView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
								scrollLinearLayout.addView(webView);
								
						
					}else {
						if(dataSet==null){
							ToastUtil.showToast(TaskDetaiSecondActivity.this,"获取数据失败");
							return;
						}
					
					tableDataSet = taskDataParser.parseFormData(dataSet);
					
					@SuppressWarnings("unchecked")
					List<EFRowSet> tableRowSets = tableDataSet.getRowSetArray();
					
					//1.生成一级item
					LayoutInflater inflater = getLayoutInflater();
					for (int i = 0;i < tableRowSets.size();i++) {
						EFRowSet tableEfRowSet = tableRowSets.get(i);
						final ViewGroup oneLayout = (ViewGroup) inflater.inflate(R.layout.task_detail_dynamic_activity_one_item, scrollLinearLayout, false);
						final RelativeLayout relativeLayout = (RelativeLayout) oneLayout.findViewById(R.id.oa_parenttitle);
						final LinearLayout linearLayout = (LinearLayout) oneLayout.findViewById(R.id.contentLinearLayout);
						TextView titleTextView = (TextView) oneLayout.findViewById(R.id.one_title);
						String title = tableEfRowSet.getString("title", "");
						oneLayout.setTag(i);
						
						titleTextView.setText(title);
						scrollLinearLayout.addView(oneLayout);
						//设置点击事件监听
						relativeLayout.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View v) {
								
								ImageView imageView = (ImageView) oneLayout.findViewById(R.id.img_arrow1);
								TextView textView = (TextView) oneLayout.findViewById(R.id.one_title);
								showOrHideGridLay(linearLayout, imageView, textView);
							}
						});
						
						//TODO 2.生成二级view
//						@SuppressWarnings("unchecked")
//						List<EFRowSet> trRowSets = tableEfRowSet.getChildDataSet().getRowSetArray();
						ViewGroup tableLayout = tableGenerator.generateTable(tableEfRowSet, getWindowManager().getDefaultDisplay().getWidth());
						linearLayout.addView(tableLayout);
						
						
					}

				}
				
				LoadingDataUtilBlack.dismiss();

			}}
			@Override
			protected void onCancelled() {
				super.onCancelled();
			}

		};
		asyncTask.executeOnExecutor(Executors.newCachedThreadPool());
	}
	

//	/**
//	 * 获取公文审批（OA）数据
//	 * 
//	 * @return
//	 */
//	private JResponseObject getOADate(String itemId) {
//		// 创建PO
//		JParamObject PO = JParamObject.Create();
//		JResponseObject RO = null;
//		String tokenConId = EnvironmentVariable.getProperty("OATokenId", "");
//
//		PO.SetValueByParamName("WB_SYS_KEY", "OA");
//		PO.SetValueByParamName("OA_params_userid", usereId);
//		PO.SetValueByParamName("OA_params_pwd", password);
//		PO.SetValueByParamName("OA_params_type", "db");
//		PO.SetValueByParamName("OA_params_tokenIDFromMoblie", tokenConId);
//		PO.SetValueByParamName("OA_params_itemId", itemId);
//		PO.SetValueByParamName("OA_systemmethod", "GetDetailHandler");
//
//		try {
//			// 连接服务器
//			RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
//			System.out.println("..........");
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//
//		return RO;
//	}
//
//	/**
//	 * 获取合同数据
//	 * 
//	 * @return
//	 */
//	private JResponseObject getContactDate(String itemId) {
//		// 创建PO
//		JParamObject PO = JParamObject.Create();
//		JResponseObject RO = null;
//		String tokenConId = EnvironmentVariable.getProperty("ContractTokenId",
//				"");
//		PO.SetValueByParamName("WB_SYS_KEY", "CONTRACT");
//		// PO.SetValueByParamName("CONTRACT_params_userid", usereId);
//		// PO.SetValueByParamName("CONTRACT_params_pwd", password);
//		PO.SetValueByParamName("CONTRACT_params_type", "1");
//		PO.SetValueByParamName("CONTRACT_params_msgid", itemId);
//		PO.SetValueByParamName("CONTRACT_params_tokenIDFromMoblie", tokenConId);
//		PO.SetValueByParamName("CONTRACT_systemmethod",
//				"GetApprovalDetailHandler");
//		try {
//			// 连接服务器
//			RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
//			System.out.println("..........");
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//
//		return RO;
//	}

}